package bom.example.common.filter;

import aom.example.security.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author X.I.O
 * @title: SqlInjectFilter
 * @projectName springboot
 * @description: TODO
 * @date 2021/10/28 11:59
 */
@Component
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "SQLInjection", initParams = { @WebInitParam(name = "regx", value = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" +
        "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)") })
public class SqlInjectFilter implements Filter {

    private String regx;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.regx = filterConfig.getInitParameter("regx");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Map parametersMap = servletRequest.getParameterMap();
        Iterator it = parametersMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String[] value = (String[]) entry.getValue();
            for (int i = 0; i < value.length; i++) {
                if(regx==null){
                    continue;
                }
                if (null != value[i] && value[i].matches(this.regx)) {
                    log.info("检测到了非法参数:"+value[i]);
                    Map map=new HashMap();
                    map.put("msg","检测到非法参数"+value[i]);
                    ResultUtil.responseJson(servletResponse,map);
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }


    @Override
    public void destroy() {}
}
